import {MapString} from "./public/sdf";
var nodejieba = require("nodejieba");

export class CutWord {

    /**
     *
     * @param str
     * @returns {any}
     */
    static getCutList(str: string): string[] {
        return nodejieba.cut(str, "Mix");
    }


    /**
     * 对长词进行二次拆分
     * @param str
     * @returns {any}
     */
    static getCutSearchList(str: string): string[] {
        return nodejieba.cutForSearch(str, true);
    }


    static buildWordMap(words: string[], str?: string|null) {
        var wordMap: MapString<boolean> = {};
        for (var u of words) {
            if (u.length == 0 || u === " " || u === "\r" || u === "\t" || u === "\n")
                continue;
            wordMap[u] = true;
        }


        if (str) {
            for (var u of str) {
                if (u === " " || u === "\r" || u === "\t" || u === "\n")
                    continue;
                wordMap[u] = true;
            }
        }
        return wordMap;
    }

    static buildUnicode36Str(wordMap: MapString<boolean>) {
        let res = "";
        for (var k in wordMap) {
            for (var i = 0; i < k.length; i++) {
                var code = k.charCodeAt(i);
                if (code > 255)
                    res += code.toString(36);
                else
                    res += k[i];
            }

            res += " ";
        }
        return res;
    }

    static buildUnicode36List(wordMap: MapString<boolean>) {
        let res: string[] = [];
        for (var k in wordMap) {
            var word = "";
            for (var i = 0; i < k.length; i++) {
                var code = k.charCodeAt(i);
                if (code > 127)
                    word += code.toString(36);
                else
                    word += k[i];
            }

            res.push(word);
        }
        return res;
    }

    /**
     * 获取Unicode36进制分词结果
     * @param str
     * @param cutOne 是否包含一元切词
     * @returns {string}
     */
    static getUnicode36(str: string, cutOne?: boolean) {
        if (!str)
            return "";
        return CutWord.buildUnicode36Str(CutWord.buildWordMap(CutWord.getCutSearchList(str), cutOne ? str : null));
    }
}